package com.muyi.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.muyi.pojo.vo.Result;
import com.muyi.service.UserService;
import com.muyi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(name = "ServletDeleteUserByIds", value = "/deleteUserByIds")
public class ServletDeleteUserByIds extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 读取请求体中的 JSON 数据
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String requestBody = sb.toString();

        // 解析 JSON 数据
        Result result = null;
        try {
            // 将请求体的 JSON 数据解析成 JSONObject
            JSONObject jsonObject = JSON.parseObject(requestBody);
            // 获取 ids 数组
            Integer[] user_ids = jsonObject.getJSONArray("ids").toArray(new Integer[0]);

            // 调用 service 层方法删除用户
            result = userService.deleteuserByIds(user_ids);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 将数据返回给前端
        response.getWriter().write(JSON.toJSONString(result));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
